package cn.t.utils;

import cn.t.constants.CommonConstants;
import cn.t.model.device.CargowaySkuDO;

import java.math.BigDecimal;

public class BusinessUtil {

    private BusinessUtil() {}

    public static BigDecimal getStockRate(Integer totalSkuInventory, Integer totalCargowayVol) {
        String stockRate;
        if (totalCargowayVol == 0) {
            stockRate = "0";
        } else {
            double deviceRatio = Double.valueOf(totalSkuInventory) / Double.valueOf(totalCargowayVol);
            stockRate = deviceRatio >= 1 ? "100" : String.format("%.2f", deviceRatio * 100);
        }
        return new BigDecimal(stockRate);
    }

    /**
     * @param diffWeight   重力差 = 后 减去 前
     * @param stdWeight    商品单重
     * @param errorRate    误差值 = 误差率*0.01*单重
     * @param correctValue 抖动平均值(默认5g)
     * @return 数量
     */
    public static Integer calcQty(BigDecimal diffWeight, BigDecimal stdWeight, BigDecimal errorRate, BigDecimal correctValue) {
        // 先取重量差绝对值
        diffWeight = diffWeight.abs();
        // 重力差=0 数量=0
        if (diffWeight.compareTo(BigDecimal.ZERO) == 0) {
            return CommonConstants.ZERO;
        }
        // 重量差小于秤的抖动误差
        if (diffWeight.compareTo(correctValue) < 0) {
            return CommonConstants.MINUS_ONE;
        }
        // 商品重量小于等于0
        if (stdWeight.compareTo(BigDecimal.ZERO) <= 0) {
            return CommonConstants.MINUS_ONE;
        }

        // 进行整除与取余 - > dr[0]：商 - > dr[1]：余数
        BigDecimal[] dr = diffWeight.divideAndRemainder(stdWeight);
        // 余数是0，整除
        if (dr[1].signum() == 0) {
            return dr[0].intValue();
        }
        // 余数<(单重/2)
        if (dr[1].compareTo(stdWeight.divide(BigDecimal.valueOf(2))) < 0) {
            // 商==0
            if (dr[0].compareTo(BigDecimal.ZERO) == 0) {
                return CommonConstants.MINUS_ONE;
            }
            return dr[0].intValue();
        } else {
            // 余数>=(单重/2)
            // 误差范围内
            if (stdWeight.subtract(dr[1]).compareTo(errorRate.multiply(dr[0].add(BigDecimal.valueOf(1)))) <= 0) {
                return dr[0].intValue() + 1;
            }
            // 误差范围外，且商==0
            if (dr[0].compareTo(BigDecimal.ZERO) == 0) {
                return CommonConstants.MINUS_ONE;
            } else {
                // 误差范围外，且商>0
                return dr[0].intValue();
            }
        }
    }
    public static Integer calcQty(CargowaySkuDO cargowaySku) {

        if (cargowaySku == null) {
            return CommonConstants.ZERO;
        }

        Integer actQty = BusinessUtil.calcQty(cargowaySku.getWeight(), cargowaySku.getSkuWeight(), new BigDecimal(cargowaySku.getErrorRate()).multiply(CommonConstants.POINT_ZERO_ONE).multiply(cargowaySku.getSkuWeight()), CommonConstants.JITTER);

        return actQty == null || actQty == -1 ? CommonConstants.ZERO : actQty;
    }
}
